/*
 *  Trie.cpp
 *  Trie
 *
 *  Created by Ariel  Rodriguez on 26/04/08.
 *  Copyright 2008 __MyCompanyName__. All rights reserved.
 *
 */

#include "Trie.h"


Trie::Trie(void){

	this->root = NULL;
	
}

TrieNode * Trie::getRoot(void){
	
	return this->root;

}

void Trie::setRoot(TrieNode * root){

	this->root = root;

}

// Funcion Private que inserta recursivamente, fijate que, 

void Trie::recursiveInsert(long int indice, TrieNode * node, char * letter){
	if( node->getNode() == NULL ){
			TrieNode * nod = new TrieNode();
			node->setNode(new nodo());
			if((*letter) == '\0'){
				(*node->getNode())[*letter] =  nod;
				nod->setNode(NULL);
				nod->setIndice(indice);
				return;
			}else{
				(*node->getNode())[*letter] = nod;
				recursiveInsert(indice , nod , ++letter);
			}
	}else{
		if((*letter == '\0')) return;
		nodo::iterator it = (*node->getNode()).find(*letter);
		if( it == (*node->getNode()).end()){
				(*node->getNode())[*letter] = new TrieNode();
				TrieNode * aux = (*node->getNode())[*letter] ;
				recursiveInsert(indice, aux , ++letter);
		}else {
			TrieNode * aux = (*node->getNode())[*letter] ;
			recursiveInsert(indice, aux , ++letter);
			
		}
	}

}

void Trie::insertKey(Key llave) {
	
	if(this->root == NULL)	this->root = new TrieNode();
	char * letter = (llave.getClave());
	long int indice = llave.getRegistro();
	this->recursiveInsert(indice, this->root, letter);
	
}

long int Trie::searchRegistry(char * letter){
	long int registro;
	if (this->root == NULL) {
		cout << "Estructura no indexada, por favor indexe(DALE LORENZOOOO):::::";
		return 0L;
	}
	(this->recursiveSearch(this->root, registro ,  letter));  
	cout << "La clave es:: "<< registro<<endl;
	return registro;
	
}

void Trie::recursiveSearch(TrieNode * node , long int & registro , char * letter){

	if ((node->getNode() == NULL) && ((node->getIndice()) != -1)){
		registro = node->getIndice();
		return;
	}
	if (node->getNode() == NULL) {
		cout << "Clave no encontrada"<<endl;
		return;
	} else {
		nodo::iterator it = (*node->getNode()).find(*letter);
		if(it == (*node->getNode()).end()){
			cout << "Clave no encontrada , LORENZO Gay:"<<endl;
		}else{
			 TrieNode * aux = (*node->getNode())[*letter];
			 recursiveSearch(aux , registro, ++letter);
		}
	}	
}
	




